package com.newbee.adapter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.gauss.render.SpeexPlayer;
import com.hhu.newbee.R;
import com.newbee.activity.tab.ConfigActivity;
import com.newbee.app.AppConfig;
import com.newbee.app.SpeechApp;
import com.newbee.fragement.multchat.MultChatFragement;
import com.newbee.http.ServerHttpUtil;
import com.newbee.listbean.ChatMsgBean;
import com.newbee.listbean.NewMsgBean.MsgType;
import com.newbee.progressdlg.PlayProgressDlg;
import com.newbee.round.CustomImageView;
import com.newbee.sound.Sound;
import com.newbee.sound.SoundRecorder;

public class ChatMsgViewAdapter extends BaseAdapter
{

	public static interface IMsgViewType
	{
		int IMVT_COM_MSG = 0;
		int IMVT_TO_MSG = 1;
	}

	private static final String TAG = ChatMsgViewAdapter.class.getSimpleName();

	private List<ChatMsgBean> coll;

	private Context ctx;

	private static final int MSG_PALY_DLG = 0;

	private static final int MSG_PLAYING = 1;
	private static final int MSG_PLAY_ERROR = 2;

	private LayoutInflater mInflater;
	private SpeexPlayer splayer = null;
	private PlayProgressDlg dlg;
	private Handler namehandler = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{

			((TextView) msg.obj).setText(msg.getData()
					.get(NewMsgListAdapter.USRNAME).toString());

		};
	};

	private Handler handler = new Handler()
	{

		@Override
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
			case MSG_PALY_DLG:
			{
				dlg.hide();

				break;
			}
			case MSG_PLAYING:
			{
				dlg.setMessage("正在播放录音 ");
				break;
			}
			case MSG_PLAY_ERROR:
			{
				dlg.setMessage("录音下载失败，请重试 ");
				break;
			}

			default:
				break;
			}
		}

	};

	public ChatMsgViewAdapter(Context context, List<ChatMsgBean> coll)
	{
		ctx = context;
		this.coll = coll;
		mInflater = LayoutInflater.from(context);
		dlg = PlayProgressDlg.createDialog(context);
		dlg.setCancelable(false);

	}

	public int getCount()
	{
		return coll.size();
	}

	public Object getItem(int position)
	{
		return coll.get(position);
	}

	public long getItemId(int position)
	{
		return position;
	}

	public int getItemViewType(int position)
	{
		// TODO Auto-generated method stub
		ChatMsgBean entity = coll.get(position);

		if (entity.getMsgType())
		{
			return IMsgViewType.IMVT_COM_MSG;
		}
		else
		{
			return IMsgViewType.IMVT_TO_MSG;
		}

	}

	public int getViewTypeCount()
	{
		// TODO Auto-generated method stub
		return 2;
	}

	public View getView(int position, View convertView, ViewGroup parent)
	{

		final ChatMsgBean entity = coll.get(position);
		boolean isComMsg = entity.getMsgType();

		final ViewHolder viewHolder = new ViewHolder();
		if (convertView == null)
		{
			if (isComMsg)
			{
				convertView = mInflater.inflate(
						R.layout.chatting_item_msg_text_left, null);
			}
			else
			{
				convertView = mInflater.inflate(
						R.layout.chatting_item_msg_text_right, null);
			}
		}
		viewHolder.tvSendTime = (TextView) convertView
				.findViewById(R.id.tv_sendtime);
		viewHolder.tvUserName = (TextView) convertView
				.findViewById(R.id.tv_username);
		viewHolder.tvContent = (TextView) convertView
				.findViewById(R.id.tv_chatcontent);
		viewHolder.tvTime = (TextView) convertView.findViewById(R.id.tv_time);
		viewHolder.head = (CustomImageView) convertView
				.findViewById(R.id.iv_userhead);
		viewHolder.isComMsg = isComMsg;
		viewHolder.tvSendTime.setText(entity.getDate());

		if (entity.getText().contains(".spx"))
		{
			viewHolder.tvContent.setText("");
			if (isComMsg)
			{
				viewHolder.tvContent.setCompoundDrawablesWithIntrinsicBounds(
						R.drawable.chatto_voice_playing_left, 0, 0, 0);
			}
			else
			{
				viewHolder.tvContent.setCompoundDrawablesWithIntrinsicBounds(0,
						0, R.drawable.chatto_voice_playing_right, 0);
			}
			viewHolder.tvTime.setText(entity.getTime());
		}
		else
		{
			viewHolder.tvContent.setText(entity.getText());
			viewHolder.tvContent.setCompoundDrawablesWithIntrinsicBounds(0, 0,
					0, 0);
			viewHolder.tvTime.setText("");
		}
		viewHolder.tvContent.setOnClickListener(new OnClickListener()
		{

			public void onClick(View v)
			{
				if (entity.getText().contains(".spx"))
				{
					// 播放声音

					// 当这个声音在本地存在的时候，直接播放，如果在本地不存在，那么我们就要上网上去下载该声音然后在播放
					File file = new File(Sound.DIR + entity.getText());

					if (file.exists() && file.length() > 0)
					{
						splayer = new SpeexPlayer(Sound.DIR + entity.getText());
						splayer.startPlay();
						dlg.setMessage("正在播放录音 ");
						dlg.show();
						Message msg = new Message();
						msg.what = MSG_PALY_DLG;
						String time = entity.getTime();
						handler.sendMessageDelayed(
								msg,
								Integer.parseInt(time.substring(0,
										time.length() - 1)) * 1000);
					}
					else
					{

						dlg.setMessage("正在下载录音文件");
						dlg.show();
						new Thread()
						{
							public void run()
							{
								// 要先下载文件，然后才能继续听到文件
								boolean re = ServerHttpUtil
										.downVoiceFileName(entity.getText());
								if (re)
								{
									splayer = new SpeexPlayer(Sound.DIR
											+ entity.getText());
									splayer.startPlay();

									handler.sendEmptyMessage(MSG_PLAYING);

									Message msg = new Message();
									msg.what = MSG_PALY_DLG;

									String time = entity.getTime();

									handler.sendMessageDelayed(msg, Integer
											.parseInt(time.substring(0,
													time.length() - 1)) * 1000);

								}
								else
								{
									handler.sendEmptyMessage(MSG_PLAYING);

									Message msg = new Message();
									msg.what = MSG_PALY_DLG;
									handler.sendMessageDelayed(msg, 2 * 1000);

								}

							};
						}.start();
					}
				}
			}
		});

		try
		{
			String userName = SpeechApp.getUserNamePair().getString(
					entity.getUserName());
			viewHolder.tvUserName.setText(userName);

		}
		catch (JSONException e1)
		{
			new Thread()
			{
				@Override
				public void run()
				{

					String str = ServerHttpUtil.getUserName(entity
							.getUserName());

					try
					{
						JSONObject jo = new JSONObject(str);
						Iterator<Object> item = jo.keys();
						if (item.hasNext())
						{
							String key = item.next().toString();
							SpeechApp.setUserNamePair(key, jo.get(key)
									.toString());

							Message msg = new Message();
							msg.obj = viewHolder.tvUserName;
							Bundle bundle = new Bundle();
							bundle.putString(NewMsgListAdapter.USRNAME,
									jo.get(key).toString());
							msg.setData(bundle);
							namehandler.sendMessage(msg);

							//
						}
					}
					catch (JSONException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}.start();
			// e1.printStackTrace();
		}

		// viewHolder.tvUserName.setText(entity.getName());
		// viewHolder.head.setImageResource(AboutMeActivity.getHeadDrawableID(entity.getHead()));

		// 这个地方的头像获取是个问题

		final String head = entity.getHead();
		final File file = new File(Environment.getExternalStorageDirectory()
				+ SpeechApp.HEAD_FILE + "/" + head + ".png");

		SoftReference<Bitmap> softReference = FriendsListvewAdapter.bitmapMap
				.get(head);
		if (softReference != null && softReference.get() != null)
		{

			Bitmap bitmap = softReference.get();

			if (bitmap != null)
			{
				viewHolder.head.setmSrc(bitmap);
				viewHolder.head.postInvalidate();
			}
			else
			{

				if (file.exists())
				{

					try
					{
						FileInputStream fis = new FileInputStream(file);
						bitmap = BitmapFactory.decodeStream(fis);
						viewHolder.head.setmSrc(bitmap);
						viewHolder.head.postInvalidate();
						fis.close();

						FriendsListvewAdapter.bitmapMap.put(head,
								new SoftReference<Bitmap>(bitmap));
					}
					catch (FileNotFoundException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					catch (IOException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
				else
				{
					new Thread(new Runnable()
					{

						public void run()
						{
							try
							{
								InputStream is = new URL(AppConfig.HTTP
										+ ServerHttpUtil.HEAD_dir + head
										+ ".png").openStream();

								Bitmap bitmap = BitmapFactory.decodeStream(is);
								is.close();
								viewHolder.head.setmSrc(bitmap);
								viewHolder.head.postInvalidate();
								FileOutputStream fis = new FileOutputStream(
										file);
								bitmap.compress(Bitmap.CompressFormat.PNG, 100,
										fis);
								fis.close();
								FriendsListvewAdapter.bitmapMap.put(head,
										new SoftReference<Bitmap>(bitmap));
							}
							catch (FileNotFoundException e)
							{
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							catch (IOException e)
							{
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}).start();
				}
			}
		}
		else
		{

			if (file.exists())
			{

				try
				{
					FileInputStream fis = new FileInputStream(file);
					Bitmap bitmap = BitmapFactory.decodeStream(fis);
					viewHolder.head.setmSrc(bitmap);
					viewHolder.head.postInvalidate();
					fis.close();

					FriendsListvewAdapter.bitmapMap.put(head,
							new SoftReference<Bitmap>(bitmap));
				}
				catch (FileNotFoundException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				catch (IOException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			else
			{
				new Thread(new Runnable()
				{

					public void run()
					{
						try
						{
							InputStream is = new URL(AppConfig.HTTP
									+ ServerHttpUtil.HEAD_dir + head + ".png")
									.openStream();

							Bitmap bitmap = BitmapFactory.decodeStream(is);
							is.close();
							viewHolder.head.setmSrc(bitmap);
							viewHolder.head.postInvalidate();
							FileOutputStream fis = new FileOutputStream(file);
							bitmap.compress(Bitmap.CompressFormat.PNG, 100, fis);
							fis.close();
							FriendsListvewAdapter.bitmapMap.put(head,
									new SoftReference<Bitmap>(bitmap));
						}
						catch (FileNotFoundException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						catch (IOException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}).start();
			}
		}
		return convertView;
	}

	static class ViewHolder
	{
		public TextView tvSendTime;
		public TextView tvUserName;
		public TextView tvContent;
		public TextView tvTime;
		public CustomImageView head;
		public boolean isComMsg = true;
	}

	public void dismissDlg()
	{
		this.dlg.dismiss();
	}
}
